package com.zzjx.listener;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.redxun.common.tool.BeanUtil;
import com.redxun.common.utils.ExceptionUtil;
import com.zzjx.datasource.DataSourceUtil;
import com.zzjx.datasource.DynamicDataSourceRegister;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.concurrent.Executor;

/**
 * 在程序启动时添加数据源。
 *
 * @author zzjx
 */
@Slf4j
public class DataSourceListener {
    private final String DATASOURCE_CONFIG = "dataSource.json";
    private final String DEFAULT_GROUP = "DEFAULT_GROUP";

    private NacosConfigProperties nacosConfigProperties;
    private String applicationName;
    private DynamicDataSourceRegister dynamicDataSourceRegister;

    public DataSourceListener(NacosConfigProperties nacosConfigProperties, DynamicDataSourceRegister dynamicDataSourceRegister, String applicationName) throws NacosException {
        this.nacosConfigProperties = nacosConfigProperties;
        this.dynamicDataSourceRegister = dynamicDataSourceRegister;
        this.applicationName = applicationName;

        nacosConfigProperties.configServiceInstance().addListener(DATASOURCE_CONFIG, DEFAULT_GROUP, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String config) {
                addDataSource();
            }
        });

        addDataSource();
    }

    private void addDataSource() {
        try {
            String config = nacosConfigProperties.configServiceInstance().getConfig(DATASOURCE_CONFIG, DEFAULT_GROUP, 0L);
            JSONObject conf = JSONObject.parseObject(config);
            if (BeanUtil.isEmpty(conf)) {
                return;
            }
            // 添加数据实例到容器中
            for (String key : conf.keySet()) {
                try {
                    JSONObject json = conf.getJSONObject(key);
                    String appName = json.getString("appName");
                    if (appName.contains(applicationName)) {
                        DataSource dataSource = DataSourceUtil.buildDataSource(key, json.getString("setting"));

                        if (dataSource != null) {
                            //数据源进行代理。
                            DataSource dsProxy = dynamicDataSourceRegister.registerDataSource(key, dataSource);
                            DataSourceUtil.addDataSource(key, dsProxy, true);
                        }
                    }
                } catch (Exception e) {
                    //错误信息
                    log.error(ExceptionUtil.getExceptionMessage(e));
                }
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getExceptionMessage(e));
        }
    }
}










